package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.AdViewTarget;
import com.wbao.dianniu.adapter.QuestAnswerAdapter;
import com.wbao.dianniu.adapter.UserInfoHolder;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.Childrens;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.data.QuestAnswerCountsData;
import com.wbao.dianniu.data.QuestAnswerListData;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.listener.IAnswerDeleteListener;
import com.wbao.dianniu.listener.IPraiseListener;
import com.wbao.dianniu.listener.IQuestAnswerListListener;
import com.wbao.dianniu.listener.IQuestAnswerListener;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.listener.IQuestDetailListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.AmDataChangeManager;
import com.wbao.dianniu.manager.AnswerDeleteManger;
import com.wbao.dianniu.manager.PraiseManger;
import com.wbao.dianniu.manager.QAnswerListManger;
import com.wbao.dianniu.manager.QuestAnswerManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestDetailManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.update.TwoComDataChangeManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.AnswerListType;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReportType;
import com.wbao.dianniu.utils.SerializableMap;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 匿名详情页
 *
 * @author yejianjun
 */
public class AmDetailActivity extends AppCompatActivity implements IQuestAnswerListListener, IQuestAnswerListener, IPraiseListener,
        IAnswerDeleteListener, OnClickListener, IQuestDelListener, TwoComDataChangeManager.ITwoComDataChangerListener,
        IQuestDetailListener, CommentLongClickHelper.ICommentLongListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private TextView adFlagTV;
    /**
     * 标题左侧的返回按键
     */
    private ImageButton backBtn;
    /**
     * 标题
     */
    private TextView titleTV;
    /**
     * 标题右边图片
     */
    private ImageButton rightImageBtn;
    /**
     * 内容
     */
    public SpanTextView contentTV;

    public ImageView adIV;
    /**
     * 转发数
     */
    public TextView forwardTV;
    /**
     * 点赞数
     */
    private TextView praiseTV;
    /**
     * 回复数
     */
    private TextView answerTV;
    private TextView deleteTV;
    private int questId;
    private QuestAnswerAdapter adapter;
    private QAnswerListManger manager;
    private QuestAnswerManager qAnswerManager;
    private QuestDelManager questDelManager;
    private QuestDetailManager questDetailManager;

    private Dialog dialog;
    private CanDoBlankGridView mGridView;
    private AnswerDeleteManger deleteManager;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;

    /**
     * 回答列表listview
     */
    private ListView myListView;

    private Map<Integer, String> replyMap = new HashMap<>();
    private QaResponse resp;

    private EmotionMainFragment emotionMainFragment;
    private EditText bar_edit_text;
    private ImageView bar_image_add_btn;
    private Button bar_btn_send;
    private CommentLongClickHelper commentLongClickHelper;
    private AmDataChangeManager amDataChangeManager;
    private PraiseManger praiseManger;
    private ImageView chosePicIV;
    private ImageView aFriendIV;
    private CheckBox checkBox;
    private View allComment;
    private TextView commentCountsTV;
    private int type = 1;
    private int type_am = 1;
    private int type_ad = 2;
    private int type_sm = 3;
    private int REQ_CODE = 120;
    private UserInfoHolder holder;
    private PullToRefreshListView pullListView;
    private boolean IsPullDown = false;
    private TwoComDataChangeManager twoComDataChangeManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_am_detail);
        initWattingView();
        initBaseView();

        pullIntentData();
        initManager();
        initEmotionMainFragment();
        reqData();
        initListener();
    }

    private void initListener() {
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                QuestAnswerListData data = (QuestAnswerListData) adapter.getItem(position - 3);
                // 进入二级回复界面
                ActivityUtils.intoTwoCommentActivity(AmDetailActivity.this, data.questId, data.id, AnswerListType.TYPE_AM, data);
            }
        });

        /*myListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom > bottom) {
                    // 打开了软键盘，触发了界面resize
                    // 隐藏下方价格，按钮
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            // 定位到底部，位置发生偏移，需要算上两个addHeadView
                            myListView.setSelection(adapter.getCount() + 1);
                        }
                    });
                } else if (bottom > oldBottom) {
                }
            }
        });*/

    }

    /**
     * 初始化管理类
     */
    private void initManager() {
        manager = new QAnswerListManger(this);
        manager.addListener(this);
        deleteManager = new AnswerDeleteManger(this);
        deleteManager.addAnswerDeleteListener(this);
        qAnswerManager = QuestAnswerManager.getInstance(this);
        qAnswerManager.addQuestAnswerListener(this);
        questDelManager = new QuestDelManager(this);
        questDelManager.addQuestDelListener(this);
        twoComDataChangeManager = TwoComDataChangeManager.getInstance();
        twoComDataChangeManager.addCommentChangeListener(this);
        questDetailManager = new QuestDetailManager(this);
        questDetailManager.addQuestDetailListener(this);
        commentLongClickHelper = CommentLongClickHelper.getInstance();
        commentLongClickHelper.addCommentLongClickListener(this);
        amDataChangeManager = AmDataChangeManager.getInstance();

    }

    /**
     * 请求数据接口顺序: 先请求心情详情，同时浏览数加一，成功后再请求问答列表
     */
    private void reqData() {
        questDetailManager.questDetail(GlobalContext.getAccountId(), questId);
    }


    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment() {
        initEmojiView();
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(pullListView, bar_image_add_btn, bar_edit_text);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void initData() {
        String id = getIntent().getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            questId = Integer.valueOf(id);
            // 单独请求下detail接口
//            questDetailManager.questDetail(GlobalContext.getAccountId(), questId);
        } else {
            int qId = getIntent().getIntExtra(Const.BUNDLE_ID, 0);
            if (qId != 0) {
                type = type_ad;
                questId = qId;
                // 单独请求下detail接口 -- 兑换列表跳转过来的
//                questDetailManager.questDetail(GlobalContext.getAccountId(), questId);
            }
        }


    }

    private void requestData(int page) {
        manager.requestAnswerList(GlobalContext.getAccountId(), String.valueOf(questId), page * PAGE_COUNTS, PAGE_COUNTS, 0);
    }

    private void addHeadView() {
        View headView;
        holder = new UserInfoHolder();
        if (type == type_ad) {
            headView = LayoutInflater.from(this).inflate(R.layout.include_ad_headview, myListView, false);
            holder.headIV = headView.findViewById(R.id.user_head);
            holder.nameTV = headView.findViewById(R.id.user_name);
            holder.labelTV = headView.findViewById(R.id.user_label);
            holder.sexIV = headView.findViewById(R.id.user_sex);
            holder.partnerIV = headView.findViewById(R.id.user_partner);
            holder.addV = headView.findViewById(R.id.add_v_iv);
            adFlagTV = headView.findViewById(R.id.hot_advert_flag);
            holder.partnerIV = headView.findViewById(R.id.user_partner);
            contentTV = headView.findViewById(R.id.qa_content_tv);
            holder.headInfoLayout = headView.findViewById(R.id.user_head_layout);
            holder.labelRelative = headView.findViewById(R.id.user_small_relative);
            adIV = headView.findViewById(R.id.am_detial_ad_iv);
            adIV.setVisibility(View.VISIBLE);
            adFlagTV.setVisibility(View.VISIBLE);
            adFlagTV.setText("广告");
            adIV.setOnClickListener(this);
            holder.headIV.setOnClickListener(this);
            holder.headInfoLayout.setOnClickListener(this);
        } else {
            headView = LayoutInflater.from(this).inflate(R.layout.qa_list_item, null);
            holder.headIV = headView.findViewById(R.id.user_head);
            holder.nameTV = headView.findViewById(R.id.user_name);
            holder.labelTV = headView.findViewById(R.id.user_label);
            holder.sexIV = headView.findViewById(R.id.user_sex);
            holder.partnerIV = headView.findViewById(R.id.user_partner);
            adFlagTV = headView.findViewById(R.id.hot_advert_flag);
            holder.addV = headView.findViewById(R.id.add_v_iv);
            holder.partnerIV = headView.findViewById(R.id.user_partner);
            contentTV = headView.findViewById(R.id.qa_content_tv);
            holder.headInfoLayout = headView.findViewById(R.id.user_head_layout);
            holder.labelRelative = headView.findViewById(R.id.user_small_relative);
            mGridView = headView.findViewById(R.id.noScroollGridView);
            if (type == type_sm) {
                holder.labelRelative.setVisibility(View.VISIBLE);
                holder.sexIV.setVisibility(View.VISIBLE);
                holder.partnerIV.setVisibility(View.VISIBLE);
                holder.headIV.setOnClickListener(this);
                holder.headInfoLayout.setOnClickListener(this);
            } else if (type == type_am) {
                holder.labelRelative.setVisibility(View.GONE);
                holder.sexIV.setVisibility(View.GONE);
                holder.partnerIV.setVisibility(View.GONE);
                adFlagTV.setVisibility(View.GONE);
            }
        }
        contentTV.setMaxLines(30);
        deleteTV = headView.findViewById(R.id.include_delete_tv);
        forwardTV = headView.findViewById(R.id.include_forward_tv);
        praiseTV = headView.findViewById(R.id.include_praise_tv);
        answerTV = headView.findViewById(R.id.include_answer_tv);
        praiseTV.setOnClickListener(this);
        deleteTV.setOnClickListener(this);
        forwardTV.setOnClickListener(this);

        myListView.addHeaderView(headView);
        allComment = LayoutInflater.from(this).inflate(R.layout.all_comment_layout, null);
        commentCountsTV = allComment.findViewById(R.id.all_comment_counts_tv);
        myListView.addHeaderView(allComment);

        adapter = new QuestAnswerAdapter(this, AnswerListType.TYPE_AM);
        myListView.setAdapter(adapter);
        headView.setOnClickListener(null);
        allComment.setOnClickListener(null);

    }

    private void initBaseView() {
        backBtn = findViewById(R.id.back_button);
        backBtn.setOnClickListener(this);
        titleTV = findViewById(R.id.title);
        titleTV.setText("查看心情");
        rightImageBtn = findViewById(R.id.right_imagebutton);
        rightImageBtn.setVisibility(View.INVISIBLE);
        rightImageBtn.setImageResource(R.drawable.sandian);
        rightImageBtn.setOnClickListener(this);

        pullListView = findViewById(R.id.am_pull_to_refresh_view);
        pullListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullListView.setOnRefreshListener(onRefreshListener);
        myListView = pullListView.getRefreshableView();
        myListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
        registerForContextMenu(myListView);
    }


    private void initEmojiView() {
        checkBox = findViewById(R.id.am_release_checkbox);
        bar_image_add_btn = findViewById(R.id.bar_image_add_btn);
        bar_btn_send = findViewById(R.id.bar_btn_send);
        bar_btn_send.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(AmDetailActivity.this, "请输入你的评论!");
                    return;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
            }
        });
        bar_edit_text = findViewById(R.id.bar_edit_text);
//        bar_edit_text.setOnClickListener(this);
        bar_edit_text.setOnEditorActionListener(actionListener);
        bar_edit_text.addTextChangedListener(watcher);
        chosePicIV = findViewById(R.id.bar_image_chose_pic);
        aFriendIV = findViewById(R.id.bar_image_a_friends);
        chosePicIV.setOnClickListener(this);
        aFriendIV.setOnClickListener(this);
        if (!GlobalContext.getPerfectData()) {
            checkBox.setVisibility(View.VISIBLE);
            checkBox.setChecked(true);
            checkBox.setButtonDrawable(R.drawable.xq_checkbox_unpress_ok);
            checkBox.setClickable(false);
        }
    }

    private void pullIntentData() {
        String id = getIntent().getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            questId = Integer.valueOf(id);
        } else {
            int qId = getIntent().getIntExtra(Const.BUNDLE_QUESTID, 0);
            questId = qId;
        }

    }

    private void showCounts(int counts) {
        String str = String.format(getResources().getString(R.string.all_comment_counts), counts + "");
        commentCountsTV.setText(str);
    }

    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }


    PullToRefreshBase.OnRefreshListener2 onRefreshListener = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh() {
            pullDownRequest();
        }

        @Override
        public void onPullUpToRefresh() {
            pullUpRequest();
        }
    };

    private void pullDownRequest() {
        IsPullDown = true;
        currentPage = 0;
        requestData(currentPage);
    }

    // 上拉刷新数据请求
    private void pullUpRequest() {
        IsPullDown = false;
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        requestData(currentPage);
//        reqestMoreData();
    }

    OnEditorActionListener actionListener = new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND /*||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)*/) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(AmDetailActivity.this, "请输入你的评论!");
                    return false;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
                return true;
            }
            return false;
        }
    };

    private void addAnswerComment(String comment) {
        // 回复之前 增加等待框
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();
        int anonymous = 0;
        if (checkBox.isChecked()) {
            anonymous = 1;
        } else {
            anonymous = 0;
        }
        qAnswerManager.addResponse(GlobalContext.getAccountId(), questId, Utils.replaceLineBlanks(comment), JsonUtil.mapToStringJson(replyMap), null, 0, anonymous);
    }

    @Override
    public void onQuestDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onQuestDelSuccess() {
        // 通知其它界面数据改变
        amDataChangeManager.notifyRemove(questId);
        this.finish();
    }

    @Override
    public void onQuestDetailFailure(int errorCode, String errorMsg) {
        if (errorCode == ErrorCode.QA_ALEARY_DEL) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
            // 问答已被删除 通知其它界面数据改变
            amDataChangeManager.notifyRemove(questId);
        } else {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
        }
    }

    @Override
    public void onQuestDetailSuccess(QaResponse response) {
        if (null != response) {
            this.resp = response;
            // 从兑换跳过来的 type没初始化，需要先初始化
            if (1 == resp.advert) {
                type = type_ad;
            } else if (0 == resp.anonymous) {
                type = type_sm;
            } else if (1 == resp.anonymous) {
                type = type_am;
            }
            addHeadView();
            display(response);
            // 请求详情成功，再请求回答列表数据
            requestData(currentPage);
        }
    }

    @Override
    public void commentLongClick(QuestAnswerListData data) {
        deleteManager.delete(data.id);
        adapter.deleteById(data.id);
        // 删除后，回复数减一
        resp.answerCount--;
        Utils.showPriseCounts(resp.answerCount, answerTV);
        showCounts(resp.answerCount);
        amDataChangeManager.replyNotify(questId, resp.answerCount);
    }

    /*private void updateCounts(QuestAnswerCountsData qacd) {
        if (null != qacd) {
            if (null == resp) {
                resp = new QaResponse();
            }
            resp.goodCount = qacd.goodCount;
            resp.answerCount = qacd.answerCount;
            resp.visitorCount = qacd.visitorCount;
            Utils.showPriseCounts(qacd.goodCount, praiseTV);
            Utils.showPriseCounts(qacd.answerCount, answerTV);
            showCounts(qacd.answerCount);
            // 通知界面 浏览数发生更新
            amDataChangeManager.updateVisitor(questId, qacd.visitorCount);
            // 通知界面 点赞数发生更新
            amDataChangeManager.priseNotify(questId, resp.isGood, qacd.goodCount);
            // 通知界面 回复数发生更新
            amDataChangeManager.replyNotify(questId, qacd.answerCount);
        }
    }*/

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.include_delete_tv:
                CustomDialog.Builder builder = new CustomDialog.Builder(AmDetailActivity.this);
                builder.setTitle("确认删除该条问答吗？");
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                questDelManager.deleteQuest(GlobalContext.getAccountId(), questId);
                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            case R.id.back_button:
                finish();
                break;
            case R.id.include_forward_tv:    // 转发
                String imageUrl = GlobalContext.cdndownUrl + resp.userInfo.headPic;
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(AmDetailActivity.this, resp.content, 1, imageUrl, questId);
                break;
            case R.id.include_praise_tv:
                if (0 == resp.isGood) {
                    resp.isGood = 1;
                    resp.goodCount++;
                } else {
                    resp.isGood = 0;
                    resp.goodCount--;
                }
                Utils.praiseChanged(this, resp.isGood, resp.goodCount, praiseTV);
                amDataChangeManager.priseNotify(questId, resp.isGood, resp.goodCount);
                // 请求点赞接口
                praiseManger = new PraiseManger(this);
                praiseManger.addPraiseListener(AmDetailActivity.this);
                praiseManger.praise(GlobalContext.getAccountId(), questId);
                // 判断以前点赞状态
                break;
            case R.id.user_head_layout:
            case R.id.user_head:
                ActivityUtils.intoHeadInfoActivity(resp.userInfo.accountId, AmDetailActivity.this);
                break;
            case R.id.right_imagebutton:
                showRealase();
                break;
            case R.id.am_detial_ad_iv:
                Intent intent = new Intent();
                intent.putExtra(Const.BUNDLE_DATA, resp.advertToPageUrl);
                intent.setClass(this, AdInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.bar_image_a_friends:
                Intent aIntent = new Intent();
                aIntent.setClass(AmDetailActivity.this, SelectFriendActivity.class);
                startActivityForResult(aIntent, REQ_CODE);
                break;
            case R.id.bar_image_chose_pic:  // 一级回复选择图片
                SerializableMap map = new SerializableMap();
                map.setMap(replyMap);
                Bundle bundle = new Bundle();
                bundle.putInt(WithPicCommentActivity.COMMENT_QUESTID, questId);
                bundle.putString(WithPicCommentActivity.Comment_Content, bar_edit_text.getText().toString());
                bundle.putString(WithPicCommentActivity.Comment_image_urls, "");
                bundle.putSerializable(WithPicCommentActivity.Comment_notice_json, map);
                bundle.putInt(WithPicCommentActivity.Comment_type, AnswerListType.TYPE_AM);
                Intent twoIntent = new Intent();
                twoIntent.putExtras(bundle);
                twoIntent.setClass(this, WithPicCommentActivity.class);
                startActivity(twoIntent);
                // 隐藏弹出的键盘...
                hideKeyboard();
                break;
            default:
                break;
        }

    }

    public boolean checkLevel() {
        boolean ret = false;
        if (GlobalContext.getPerfectData()) {
            // 提示用户完成认证 必须达到一级认证才能提问
            ret = true;
        }
        return ret;
    }

    /**
     * 显示弹出框
     */
    private void showRealase() {
        commentLongClickHelper.showReportDialog(this, ReportType.TYPE_QA, questId);
    }

    @Override
    public void onPraiseFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onPraiseSuccess() {

    }

    @Override
    public void onQuestAnswerFailure(int errorCode, String errorMsg) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (errorCode == ErrorCode.QA_ALEARY_DEL) {
            // 问答已被删除 通知其它界面数据改变
            amDataChangeManager.notifyRemove(questId);
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onQuestAnswerSuccess(QuestAnswerListData qacd) {
        // TODO Auto-generated method stub
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        // 评论完成 添加一条记录到回复列表
        if (null != qacd) {
            //通过pid判断是1级回复还是二级回复 pid不为0 则为二级回复
            if (0 != qacd.pid) {
                return;
            }

            bar_edit_text.setText("");
            bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
            if (null != replyMap) {
                replyMap.clear();
            }
            qacd.accountId = GlobalContext.getAccountId();
            qacd.goodCount = 0;
            adapter.addOneData(qacd);
            adapter.notifyDataSetChanged();
            // 添加一条回答数
            resp.answerCount++;
            Utils.showPriseCounts(resp.answerCount, answerTV);
            showCounts(resp.answerCount);
            // 通知界面更新回答列表
            amDataChangeManager.replyNotify(questId, resp.answerCount);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    // 定位到最上面一条数据，位置发生偏移，需要加上两个addHeadview的内容
//                    myListView.getHeaderViewsCount();
                    myListView.setSelection(2);
                }
            });
        }
    }

    @Override
    public void onQuestAnswerListFailure(int errorCode, String errorMsg) {
        if (errorCode == ErrorCode.QA_ALEARY_DEL) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
            // 问答已被删除 通知其它界面数据改变
            amDataChangeManager.notifyRemove(questId);
        } else {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
        }
    }

    @Override
    public void onQuestAnswerListSuccess(List<QuestAnswerListData> objdata, QuestAnswerCountsData qacd) {
        waittingLayout.setVisibility(View.GONE);
        pullListView.onRefreshComplete(false, false);
        if (null != objdata) {
            if (IsPullDown) {
                adapter.clear();
            }
            adapter.addData(objdata);
            adapter.notifyDataSetChanged();
        }
    }

    private void display(QaResponse response) {
        if (null == response)
            return;
        this.resp = response;
        PictureDownloadUtils.displayHeadImage(this, holder.headIV, resp.userInfo.headPic);
        holder.nameTV.setText(resp.userInfo.realName == null ? "" : resp.userInfo.realName);
        holder.labelTV.setText(resp.userInfo.label == null ? "" : resp.userInfo.label);
        // 广告和自己的问答详情-- 隐藏右上角三点 其他的显示
        if (resp.userInfo.accountId == GlobalContext.getAccountId()) {
            deleteTV.setVisibility(View.VISIBLE);
            rightImageBtn.setVisibility(View.GONE);
        } else {
            deleteTV.setVisibility(View.INVISIBLE);
            rightImageBtn.setVisibility(View.VISIBLE);
        }
        Utils.showAuth(resp.userInfo, holder.addV);

        if (type == type_ad) {
            rightImageBtn.setVisibility(View.GONE);
            Utils.showSex(this, resp.userInfo.sex, holder.sexIV);
            Utils.showPartner(this, resp.userInfo.partner, holder.partnerIV);
            if (TextUtils.isEmpty(resp.questImgs)) {
                adIV.setVisibility(View.GONE);
            } else {
                adIV.setVisibility(View.VISIBLE);
                adIV.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                        if (null == imageUrls || imageUrls.size() == 0) {
                            return;
                        }
                        Glide.with(AmDetailActivity.this)
                                .load(imageUrls.get(0))
                                .asBitmap()
                                .into(new AdViewTarget(adIV));
                    }
                }, 200);
            }
        } else {
            if (type == type_sm) {
                Utils.showSex(this, resp.userInfo.sex, holder.sexIV);
                Utils.showPartner(this, resp.userInfo.partner, holder.partnerIV);
            }
            // 图片显示
            if (TextUtils.isEmpty(resp.questImgs)) {
                mGridView.setVisibility(View.GONE);
            } else {
                mGridView.setVisibility(View.VISIBLE);
                Utils.showGridView(this, resp.questImgs, mGridView, false, true);
            }

        }


        contentTV.setMovementMethod(LinkMovementMethod.getInstance());
        contentTV.setAutoLinkMask(Linkify.WEB_URLS);
        contentTV.setEmojiText(resp.content, resp.noticeJson);
        contentTV.setOnLongClickListener(longClickListener);
        Utils.showPriseCounts(resp.answerCount, answerTV);
        showCounts(resp.answerCount);
        Utils.praiseChanged(this, resp.isGood, resp.goodCount, praiseTV);

        /**
         // 通知界面 浏览数发生更新
         amDataChangeManager.updateVisitor(resp.id, resp.visitorCount);
         // 通知界面 点赞数发生更新
         amDataChangeManager.priseNotify(resp.id, resp.isGood, resp.goodCount);
         // 通知界面 回复数发生更新
         amDataChangeManager.replyNotify(resp.id, resp.answerCount);
         */
    }

    @Override
    public void onAnswerDeleteFailure(int errorCode, String errorMsg) {
    }

    @Override
    public void onAnswerDeleteSuccess() {
    }

    OnLongClickListener longClickListener = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            showCopyDialog();
            return true;
        }
    };

    /**
     * 显示复制取消弹出框
     */
    private void showCopyDialog() {
        commentLongClickHelper.showCopyDialog(this, contentTV.getText().toString());
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        ReplyHelper.getInstance().removeReplyListener(this);
        if (null != commentLongClickHelper)
            commentLongClickHelper.removeCommentLongClickListener(this);
        if (null != twoComDataChangeManager) {
            twoComDataChangeManager.removeCommentChangeListener(this);
        }
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (null != questDetailManager) {
            questDetailManager.removeQuestDetailListener(this);
        }
        if (null != manager) {
            manager.removeListener(this);
        }
        if (null != deleteManager) {
            deleteManager.removeAnswerDeleteListener(this);
        }
        if (null != qAnswerManager) {
            qAnswerManager.removeQuestAnswerListener(this);
        }
        if (null != questDelManager) {
            questDelManager.removeQuestDelListener(this);
        }
        if (null != praiseManger) {
            praiseManger.removePraiseListener(this);
        }
        // 移除绑定的EditText
        if (null != emotionMainFragment) {
            emotionMainFragment.removeEditText();
        }
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                // 清空输入内容时，清除@效果的hashMap
                bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
                if (null != replyMap) {
                    replyMap.clear();
                }
            }
        }
    };

    float previousX = 0;
    float previousY = 0;
    float softHeight = 0;
    boolean inOutside = true;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                previousX = ev.getRawX();
                previousY = ev.getRawY();
                int[] l = {0, 0};
                bar_image_add_btn.getLocationInWindow(l);
                softHeight = l[1];
                inOutside = ev.getY() < softHeight;
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = previousY - ev.getRawY();
                float dx = previousX - ev.getRawX();
                if ((Math.abs(dy) > 30 || Math.abs(dx) > 30) && inOutside) {
                    hideKeyboard();
                }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        emotionMainFragment.onBackPress();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE) {
            if (resultCode == RESULT_OK) {
                String userName = data.getStringExtra(Const.INTENT_NICENAME);
                int friendId = data.getIntExtra(Const.BUNDLE_ACCOUNTID, 0);
                if (userName != null && 0 != friendId) {
                    replyMap.put(friendId, userName);// 加入noticeJson
                    // 光标出插入@
                    int index = bar_edit_text.getSelectionStart();
                    Editable editable = bar_edit_text.getText();
                    editable.insert(index, "@" + userName);
                }
            }
        }
    }

    @Override
    public void addOneTwoCommentData(int id, Childrens childrens) {
        adapter.addOneTwoComment(id, childrens);
    }

    @Override
    public void delOneTwoCommentData(int id, int childId) {
        adapter.removeOneTwoComment(id, childId);
        myListView.setAdapter(adapter);
    }

    @Override
    public void priseCommentNotify(int id, int isGood, int goodCounts) {
        //点赞数发生改变
        adapter.priseNotify(id, isGood, goodCounts);
    }

    @Override
    public void replyCommentNotify(int id, int answerCounts) {

    }
}
